package org.wrigut.parser;

import org.wrigut.scanlib.Token;
import java.util.Stack;

/* TreeReader.java
 * 
 * Project 1 - CS 3361
 * 
 * Authors: Chris Gutierrez
 *          Jordan Wright
 */

public class TreeReader {
	private ParseTree tree;
	private Stack<Object> branch;
	private Stack<Integer> indices;
	private String prefix = "";
	
	public TreeReader(ParseTree tree) {
		this.tree = tree;
		branch = new Stack<Object>();
		indices = new Stack<Integer>();
		branch.push(this.tree);
		indices.push(-1);
	}
	
	public String getLine() {
		String output = null;
		if (branch.size() == 0) return null;
		if (branch.peek() instanceof Token) {
			//Stack top: Token
			Token t = (Token) branch.peek();
			switch (indices.peek()) {
			case -1:
				output = prefix+"<"+t.getType()+">";
				setTop(0);
				break;
			case 0:
				output = prefix+"\t"+t.getValue();
				setTop(1);
				break;
			case 1:
				output = prefix+"</"+t.getType()+">";
				branch.pop();
				indices.pop();
				prefix = prefix.substring(1);
				break;
			}
		} else {
			//Stack top: ParseTree
			ParseTree node = (ParseTree) branch.peek();
			int index = indices.peek();
			if (index == -1) {
				output = prefix+"<"+node+">";
				setTop(1);
				if (node.getSize() > 0) {
					prefix += "\t";
					branch.push(node.getBranch(0));
					indices.push(-1);
				}
			} else if (index >= node.getSize()) {
				output = prefix+"</"+node+">";
				branch.pop();
				indices.pop();
				if (!prefix.isEmpty()) prefix = prefix.substring(1);
			} else {
				setTop(index+1);
				prefix += "\t";
				branch.push(node.getBranch(index));
				indices.push(-1);
				output = getLine();
			}
		}
		return output;
	}
	
	private void setTop(int index) {
		indices.set(indices.size()-1, index);
	}
}
